import 'package:flutter/material.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/event/event.dart';
import 'package:osc/event/event_constant.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/pd_text_field.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_log.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool loginSuccess = false;
  bool remember = true;
  String account = "";
  String password = "";
  TextEditingController userNameController = new TextEditingController();
  TextEditingController passwordController = new TextEditingController();

  FocusNode fnName = FocusNode();
  FocusNode fnPwd = FocusNode();

  @override
  void initState() {
    super.initState();
    account = OscUserManager.instance.getAccount();
    password = OscUserManager.instance.getPassword();
    userNameController.text = account;
    passwordController.text = password;
  }

  @override
  Widget build(BuildContext context) {
    return  CommonScaffold(
      title: StringIds.login,
      body: SingleChildScrollView(
        padding:
        EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_activity_vertical),
        child: Column(
          children: <Widget>[
            PdTextField(
              icon: Icon(Icons.person),
              hintText: "请输入账号",
              controller: userNameController,
              focusNode: fnName,
            ),
            PdTextField(
              icon: Icon(Icons.lock),
              hintText: "请输入密码",
              obscureText: true,
              margin: EdgeInsets.only(top: Dimens.gap_view_big),
              controller: passwordController,
              focusNode: fnPwd,
            ),
            Container(
              margin: EdgeInsets.only(top: Dimens.gap_view_big),
              child: Row(
                children: <Widget>[
                  Expanded(
                      child: Container(
                        height: Dimens.view_button_height_normal,
                        child: RaisedButton(
                          child: Text(StringIds.login),
                          textColor: Colors.white,
                          color: Colors.green,
                          elevation: 2,
                          onPressed: () {
                            login(context);
                          },
                        ),
                      )),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: Dimens.gap_view_normal),
              child: new GestureDetector(
                onTap: () {
                  setState(() { remember = !remember; });
                },
                child: Row(
                  children: <Widget>[
                    Icon(remember?Icons.check_box:Icons.check_box_outline_blank, color: remember?Colors.green:Colors.black54,),
                    Text("记住密码"),
                  ],
                ),
              ),
            ),

            Container(
              margin: EdgeInsets.only(top: Dimens.gap_view_normal),
              child:
              Row(
                children: <Widget>[
                  new GestureDetector(
                    onTap: () {
//                      push2Page(context, new RegisterPage());
                    },
                    child: Row(
                      children: <Widget>[
                        Text("注册新用户"),
                      ],
                    ),
                  ),
                  Expanded(child: Text("")),
                  new GestureDetector(
                    onTap: () {
//                      push2Page(context, new ResetPasswordPage(pageType: RegisterAndResetPasswordWidget.PAGE_TYPE_FORGET_PWD));
                    },
                    child: Row(
                      children: <Widget>[
                        Text("忘记密码?"),
                      ],
                    ),
                  ),
                ],
              ),
            )

          ],
        ),
      ),
    );
  }


  login(BuildContext context) async {
    account = userNameController.text;
    password = passwordController.text;
    FocusScopeNode focusScopeNode = FocusScope.of(context);
    if (account.isEmpty) {
      showToast("请输入用户名!");
      focusScopeNode.requestFocus(fnName);
    } else if (password.isEmpty) {
      showToast("请输入密码!");
      focusScopeNode.requestFocus(fnPwd);
    } else {
      await new HttpRepository().login(account:account, password:StringUtil.getEncodePassword(password)).then((resp) {
        loginSuccess = resp.success;
        if (!loginSuccess) {
          showToast(resp.message);
        } else {
          OscUserManager.instance.setLogin(true);
          OscUserManager.instance.setRememberPwd(remember);
          if(remember){
            OscUserManager.instance.setAccount(account);
            OscUserManager.instance.setPassword(password);
          }
          OscUser user = resp.result;
          if(user != null) {
            OscUserManager.instance.setUser(user);
          }
          eventBus.emit(EventConstant.LOGIN);
          PdLog.printLog("-****** emit login");
          showToast("登录成功");
          PopResult result = PopResult(id: PopResult.ID_LOGIN, success: true, object: user);
          if(mounted){
            Navigator.pop(context, result);
          }
        }
      });
    }
  }

  push2Page(BuildContext context, Widget page){
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result){
      if(result != null && result.success){
        setState(() {
          userNameController.text = OscUserManager.instance.userName;
          passwordController.text = OscUserManager.instance.password;
        });
      }
    });
  }

  showToast(String msg) {
    PdUtil.showToast(msg: msg);
  }
}
